import WorldMod from "../../model/WorldMod";
import { ClientEvent } from "../../event/ClinetEvent";
import IMsg, { MsgType, IMsgKill, IMsgWall, IMsgPlayer } from "../../../common/game/world/Msg";
import SnakeMod from "../../model/SnakeMod";
import Timer from "../../../common/core/Timer";
import BaseView from "../../core/mvc/BaseView";

const { ccclass, property } = cc._decorator;
const et = ClientEvent.Type

interface IMsgShow {
    str: string
    color?: string,
}

const key_show = "msg_show"

@ccclass
export default class UIMsg extends BaseView {


    /** 消息预制体 */
    @property(cc.Prefab)
    msgPre: cc.Prefab = null

    /** 最多显示几条 */
    maxShowMsg: number = 10

    _worldMod: WorldMod
    _snakeMod: SnakeMod

    _timer: Timer = new Timer()

    _msgs: IMsg<any>[] = []

    msgPool: cc.NodePool = null

    getMsgNode() {
        return this.msgPool.get() || cc.instantiate(this.msgPre)
    }

    delMsgNode(node: cc.Node) {
        this.msgPool.put(node)
    }

    start() {
        this._worldMod = WorldMod.ins
        this._snakeMod = SnakeMod.ins

        this.ed.on(et.MSGS, this, e => {
            this._msgs = this._msgs.concat(e.msgs)
        })

        this._timer.set(key_show, 100)

        this.msgPool = new cc.NodePool()
    }

    update() {
        if (this._msgs.length) {
            this._timer.check(key_show, () => {
                this.showMsg(this._msgs.shift())
            })
        }
    }

    showMsg(msg: IMsg<any>) {
        if (this.node.children.length > this.maxShowMsg) {
            this.delMsgNode(this.node.children[0])
        }
        let show = this.getMsgShow(msg)
        //生成消息节点
        let msgNode = this.getMsgNode()
        msgNode.getComponent(cc.Label).string = show.str
        msgNode.color = cc.color(show.color)
        msgNode.parent = this.node
    }


    getMsgShow(msg: IMsg<any>): IMsgShow {
        switch (msg.type) {
            case MsgType.player:
                let pd: IMsgPlayer = msg.data
                let flag = pd.flag == 1 ? "加入" : "退出"
                return {
                    str: `<${this._snakeMod.getSnake(pd.snakeId).name}> ${flag}了游戏！`,
                    color: "#ff00aa"
                }
            case MsgType.kill:
                let kd: IMsgKill = msg.data
                return {
                    str: `<${this._snakeMod.getSnake(kd.snakeId).name}> 一头撞上了 <${this._snakeMod.getSnake(kd.killerId).name}> ！`,
                    color: "#00eeff"
                }
            case MsgType.wall:
                let wd: IMsgWall = msg.data
                return {
                    str: `<${this._snakeMod.getSnake(wd.snakeId).name}> 狠狠地撞在了墙上！`,
                    color: "#ff0000"
                }
        }
    }

}
